<template>
  <div>
    <div style="margin-left: 80%;">
      <el-button @click="downloadPie" icon="el-icon-download">下载</el-button>
    </div>
    <div class="echart" ref="mychart" id="mychart"
      :style="{ float: 'left', width: '100%', height: '366px', background: '#fff' }"></div>
  </div>
</template>

<script>
import * as echarts from "echarts"
import bus from '@/views/dashboard/bus'

export default {
  data() {
    return {
      total: {
        multimodal_video: 0,
        multimodal_text: 0,
        multimodal: 0,
        multimodal_audio: 0,
        multimodal_image: 0,
        article: 0
      }
    };
  },
  mounted() {
    bus.$on('pieData', data => {
      this.total = data;
      this.initEcharts();
    });
  },
  methods: {
    initEcharts() {
      const option = {
        // 图例
        legend: {
          data: [
            { name: '图片', icon: 'circle' },
            { name: '视频', icon: 'circle' },
            { name: '音频', icon: 'circle' },
            { name: '文本', icon: 'circle' }
          ],
          left: 'center', // 将图例居中放置
          // 将图例放置在饼图下方
          top: "auto",
          bottom: "3%", // 调整图例距离底部的位置
          orient: "horizontal" // 设置图例为水平布局
        },
        // 标题
        title: {
          text: "多模态资源占比",
          top: "3%",
          left: "center"
        },
        series: [
          {
            type: "pie",
            radius: ['25%', '70%'], // 调整饼图的大小，第一个值是内半径，第二个值是外半径
            label: {
              show: true,
              formatter: "{b} : {c} ({d}%)", // b代表名称，c代表对应值，d代表百分比
              position: 'inside'
            },
            data: [
              { value: this.total.multimodal_image, name: '图片' },
              { value: this.total.multimodal_video, name: '视频' },
              { value: this.total.multimodal_audio, name: '音频' },
              { value: this.total.multimodal_text + this.total.article, name: '文本' }
            ]
          }
        ]
      };
      const myChart = echarts.init(this.$refs.mychart);// 图标初始化
      myChart.setOption(option);// 渲染页面      
      //随着屏幕大小调节图表
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },
    downloadPie() {
      let canvas = document.getElementsByTagName("canvas");
      if (canvas && canvas.length > 0) {
        // 创建标签
        let tempA = document.createElement("a");
        // 设置下载名称
        tempA.download = "多模态资源占比图" + ".png";
        // 设置地址以及文件类型
        tempA.href = canvas[1].toDataURL("image/png");
        document.body.appendChild(tempA);
        tempA.click();
        tempA.remove();
      }
    },
  },
  beforeDestroy() {
    bus.$off('pieData');
  }
};
</script>